<?

/**
 * Database connection class, it is single pattern so always we get one instance of the connection for each request.
 * @author Muhammad.
 */
class DatabaseConnection
{
    
    private $host;
    private $user;
    private $password;
    private $database;
    private $link;
    // Store the single instance of Database
    private static $instance = NULL;
    private $saveLog = false;
    /**
     *
     * @var <array>
     */
    private static $queryLog = array();

    // Private constructor to limit object instantiation to within the class
    private function __construct( $server = DB_SERVER, $user = DB_USER, $password = DB_PASS, $database = "ssense" )
    {
        
        $this->host = $server;
        $this->user = $user;
        $this->password = $password;
        $this->database = $database;
        
        $this->link = mysql_connect($this->host, $this->user, $this->password);

        if( !$this->link )
        {
            //throw new Exception('failed to open the connection with the database');
			//$err->error(__CLASS__.' error, '.print_r($db, true).', link='.$this->link);
			die ('failed to open the connection with the database');
        }
		else
		{
			//$err->error(__CLASS__.' ok, link='.$this->link);
		}
        
        mysql_select_db($this->database, $this->link) or die('failed connecting to database 1');
        if( !mysql_select_db($this->database, $this->link) )
        {
            //throw new Exception('failed connecting to database');
			die ('failed connecting to database');
        }
    }

    // Getter method for creating/returning the single instance of this class
    /*
     * @return DatabaseConnection
     */
    public static function connect( $server, $user, $password, $database )
    {
       
		
		if( !self::$instance instanceof DatabaseConnection )
        {
            self::$instance = new DatabaseConnection($server, $user, $password, $database);
        }
        
        return self::$instance->link;
    }

    /*
     * @return DatabaseConnection
     */
    public static function getInstance()
    {
        if( !self::$instance instanceof DatabaseConnection )
        {
            return NULL;
        }
        else
        {
            return self::$instance;
        }
    
    }

    public function getLink()
    {
        return $this->link;
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

    public function __destruct()
    {
        new Query('SET AUTOCOMMIT=1');
        //$err = new errorControl();
		/*
		if($this->link)
		{
			$res=mysql_close($this->link);
			$err->error($res? __CLASS__.' Mysql Connection closed':__CLASS__.' Mysql Connection not closed');
		}	
		else $err->error(__CLASS__.' Mysql Connection link is absent');
		*/
		if( $this->saveLog )
        {
            $this->saveLog();
        }
    }

    public function logQuery( $queryStr )
    {
        
        $this->queryLog[] = $queryStr;
    }

    public static function dumpLog()
    {
        echo '<pre>';
        print_r(self::$queryLog);
        echo '</pre>';
    }

    private function saveLog()
    {
        $logFile = Utility::getRealPath(DIR_BASE . 'log/database/queries.log');
        
        $fh = fopen($logFile, 'a+');
        fputs($fh,  "---------------------------------------------------------------------------------------");
        fputs($fh,  "---------------------------------------------------------------------------------------");
        fputs($fh,  "\r\n");
        fputs($fh,  sprintf("REQUEST AT:  %s \r\n", time()));
        fputs($fh,  sprintf("URI:  %s \r\n", $_SERVER['REQUEST_URI']) );
        fputs($fh,  sprintf("QUERY STRING: %s  \r\n", $_SERVER['QUERY_STRING'] ));
        fputs($fh,  "\r\n\r\n");
        foreach( $this->queryLog as $query )
        {
          fputs($fh,  $query."\r\n\r\n");  
          //  fwrite($fh, $query . "\n");
        }
        fputs($fh,  "\r\n\r\n");
        fclose($fh);
    
    }

}

?>